package com.example.cinema.service;

import com.example.cinema.dto.ScheduleDTO;
import com.example.cinema.model.Movie;
import com.example.cinema.model.Schedule;
import com.example.cinema.model.Seat;
import com.example.cinema.repository.MovieRepository;
import com.example.cinema.repository.ScheduleRepository;
import com.example.cinema.repository.SeatRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ScheduleService {

    private final ScheduleRepository scheduleRepository;
    private final MovieRepository movieRepository;
    private final SeatRepository seatRepository;

    @Autowired
    public ScheduleService(ScheduleRepository scheduleRepository, MovieRepository movieRepository, SeatRepository seatRepository) {
        this.scheduleRepository = scheduleRepository;
        this.movieRepository = movieRepository;
        this.seatRepository = seatRepository;
    }

    // 添加排片并生成座位
    @Transactional
    public Schedule create(ScheduleDTO dto) {
        // 检查电影是否存在
        Movie movie = movieRepository.findById(dto.getMovie_id())
                .orElseThrow(() -> new RuntimeException("电影不存在: " + dto.getMovie_id()));

        // 创建排片
        Schedule schedule = new Schedule(movie, dto.getStart_time(), dto.getPrice());
        Schedule savedSchedule = scheduleRepository.save(schedule);

        // 生成80个座位(8行10列)
        int seatCount = 0;
        for (int row = 1; row <= 8; row++) {
            for (int col = 1; col <= 10; col++) {
                Seat seat = new Seat(savedSchedule, row, col);
                seatRepository.save(seat);
                seatCount++;
            }
        }
        System.out.println("为排片ID: " + savedSchedule.getId() + " 创建了 " + seatCount + " 个座位");

        return savedSchedule;
    }

    // 获取所有排片
    public List<ScheduleDTO> getAllSchedules() {
        return scheduleRepository.findAll().stream()
                .map(schedule -> new ScheduleDTO(
                        schedule.getId(),
                        schedule.getMovie().getId(),
                        schedule.getStart_time(),
                        schedule.getPrice()))
                .collect(Collectors.toList());
    }

    // 根据ID获取排片
    public ScheduleDTO getScheduleById(Integer id) {
        Schedule schedule = scheduleRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("排片不存在: " + id));

        return new ScheduleDTO(
                schedule.getId(),
                schedule.getMovie().getId(),
                schedule.getStart_time(),
                schedule.getPrice());
    }

    // 获取排片详情(包含座位信息)
    public ScheduleWithSeatsDTO getScheduleWithSeats(Integer id) {
        Schedule schedule = scheduleRepository.findByIdWithMovie(id)
                .orElseThrow(() -> new RuntimeException("排片不存在: " + id));
    
        List<Seat> seats = seatRepository.findByScheduleId(id);
        if (seats.isEmpty()) {
            System.out.println("警告: 排片ID " + id + " 没有找到对应的座位数据");
            // 如果没有座位数据，手动创建
            createSeatsForSchedule(schedule);
            seats = seatRepository.findByScheduleId(id);
            System.out.println("已为排片ID " + id + " 自动创建 " + seats.size() + " 个座位");
        }
    
        return new ScheduleWithSeatsDTO(
                schedule.getId(),
                schedule.getMovie().getId(),
                schedule.getMovie().getTitle(),
                schedule.getStart_time(),
                schedule.getPrice(),
                seats);
    }

    // 手动创建座位的方法（可选）
    @Transactional
    private void createSeatsForSchedule(Schedule schedule) {
        for (int row = 1; row <= 8; row++) {
            for (int col = 1; col <= 10; col++) {
                Seat seat = new Seat(schedule, row, col);
                seatRepository.save(seat);
            }
        }
    }

    // 创建内部类用于返回排片详情(包含座位)
    public static class ScheduleWithSeatsDTO {
        private Integer id;
        private Integer movie_id;
        private String movie_title;
        private java.time.LocalDateTime start_time;
        private java.math.BigDecimal price;
        private List<Seat> seats;

        public ScheduleWithSeatsDTO(Integer id, Integer movie_id, String movie_title, java.time.LocalDateTime start_time, java.math.BigDecimal price, List<Seat> seats) {
            this.id = id;
            this.movie_id = movie_id;
            this.movie_title = movie_title;
            this.start_time = start_time;
            this.price = price;
            this.seats = seats;
        }

        // getter和setter方法
        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public Integer getMovie_id() {
            return movie_id;
        }

        public void setMovie_id(Integer movie_id) {
            this.movie_id = movie_id;
        }

        public String getMovie_title() {
            return movie_title;
        }

        public void setMovie_title(String movie_title) {
            this.movie_title = movie_title;
        }

        public java.time.LocalDateTime getStart_time() {
            return start_time;
        }

        public void setStart_time(java.time.LocalDateTime start_time) {
            this.start_time = start_time;
        }

        public java.math.BigDecimal getPrice() {
            return price;
        }

        public void setPrice(java.math.BigDecimal price) {
            this.price = price;
        }

        public List<Seat> getSeats() {
            return seats;
        }

        public void setSeats(List<Seat> seats) {
            this.seats = seats;
        }
    }
}